package com.mrd.gtimp.business.action;

import com.mrd.constant.MsgConstants;
import com.mrd.constant.RoleConstants;
import com.mrd.constant.SystemConstants;
import com.mrd.exception.QueryException;
import com.mrd.framework.config.web.json.Result;
import com.mrd.framework.ui.Jqgrid;
import com.mrd.framework.ui.filter.Filter;
import com.mrd.framework.ui.filter.FilterGroupOption;
import com.mrd.framework.ui.filter.SearchRule;
import com.mrd.framework.ui.filter.SearchRuleOption;
import com.mrd.framework.utils.HttpUtils;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimp.business.entity.BizFlow;
import com.mrd.gtimp.business.service.BizFlowBiz;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;

import javax.annotation.Resource;

import static com.mrd.util.AdminUtil.checkRight;

/**
 * <p> application name: gtimp <p> copyright: Copyright@2012 明睿达科技有限公司
 */

/**
 * @author luob
 */

@Controller
@RequestMapping("/business")
public class BizFlowAction {
    private static final long serialVersionUID = 1L;
    @Resource
    private BizFlowBiz bizFlowBiz;

    /**
     * 默认访问入口
     */
    @RequestMapping("/bizFlow-main")
    public String main() {
        return "main";
    }

    /**
     * 默认新增修改入口
     */
    @RequestMapping("/bizFlow-manage")
    public String manage() {
        return "manage";
    }

    /**
     * 可选供应商跳转页面
     */
    @RequestMapping("/bizFlow-supChoiceList")
    @ResponseBody
    public Result supChoiceList(String com_type, String sup_type, String id, Model model) {
        Result msg;
        com_type = "CC";
        sup_type = HttpUtils.getParam("sup_type");
        id = HttpUtils.getParam("id");
        if ("C".equals(sup_type)) {
//            title = "订舱业务";
            model.addAttribute("title", "订舱业务");
        } else if ("D".equals(sup_type)) {
//            title = "报关报检业务";
            model.addAttribute("title", "报关报检业务");
        } else if ("F".equals(sup_type)) {
//            title = "拖车业务";
            model.addAttribute("title", "拖车业务");
        } else {
            msg = Result.newFailInstance(MsgConstants.OPERATION_FAIL);
            return msg;
        }
        return Result.newSuccessInstance("/gtimp/business/supChoiceList");
    }

    /**
     * 保存业务流转
     */
    @RequestMapping("/bizFlow-validateSaveFlow")
    @ResponseBody
    public Result validateSaveFlow(User user, BizFlow bizFlow, String id) {
        Result msg;
        try {
            String scompany = user.getCompany().getId();
            String tcompany = HttpUtils.getParam("supChoice");
            bizFlow = new BizFlow();
            bizFlow.setCtime(new Date());
            bizFlow.setOperator(user);
            bizFlow.setOperatorExt(user.getAccount());
            bizFlow.setScompany(scompany);
            bizFlow.setTcompany(tcompany);
            bizFlow.setBizId(id);

            String sql = "select type from T_BIZ_BASE_BUSINESS where id='" + id + "'";
            String type = "";
            type = bizFlowBiz.findObjectBySql(sql, 0, 1, null).get(0).toString();
            bizFlow.setType(type);

            bizFlowBiz.updateValidateFlow(bizFlow);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
            return msg;
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL);
            return msg;
        }
    }

    /**
     * 新增或修改信息
     */
    @RequestMapping("/bizFlow-saveOrUpdate")
    public Result saveOrUpdate(BizFlow bizFlow) {
        Result msg;
        //// TODO: 2016/8/13
//        if (checkRight(RoleConstants.SUP_CUSTOMER_SAVE)) {
        try {
            if (StringUtils.isEmpty(bizFlow.getId())) { // 新增操作
                // bizFlow.setCOM_ID(user.getCompany().getId());
                // bizFlow.setCREATOR(user.getAccount());
                // bizFlow.setCTIME(new Date());
                bizFlow.setId(null);
            } else { // 修改操作
                // bizFlow.setMODIFIER(user.getAccount());
                // bizFlow.setMTIME(new Date());
            }
            bizFlowBiz.saveOrupdateEntity(bizFlow);
            msg = Result.newSuccessInstance(MsgConstants.SAVE_SUECCES);
        } catch (Exception e) {
            e.printStackTrace();
            msg = Result.newFailInstance(MsgConstants.SAVE_FAIL + e.getMessage());
//        }
            return msg;
        }

        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 编辑信息
     */
    @RequestMapping("/bizFlow-find")
    public BizFlow find(BizFlow bizFlow) {
        if (null != bizFlow) {
            if (StringUtils.isNotEmpty(bizFlow.getId())) {
                try {
                    bizFlow = bizFlowBiz.findEntityById(bizFlow.getId());
                    return bizFlow;
                } catch (QueryException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * 删除信息
     */
    @RequestMapping("/bizFlow-del")
    @ResponseBody
    public Result del(Filter filters) {
        Result msg;
        if (checkRight(RoleConstants.SUP_CUSTOMER_DEL)) {
            try {
                String ids = HttpUtils.getParam("id");
                String[] idArr = ids.split(",");
                StringBuffer sb = new StringBuffer();
                for (String string : idArr) {
                    sb.append("'").append(string).append("',");
                }
                if (sb.length() > 0) {
                    sb.deleteCharAt(sb.length() - 1);
                    filters = new Filter();
                    filters.setGroupOp(FilterGroupOption.AND);
                    filters.addRule(new SearchRule("id", SearchRuleOption.in, sb.toString()));
                    bizFlowBiz.deleteByFilter(filters);
                }
                msg = Result.newSuccessInstance(MsgConstants.DEL_SUCCES);
            } catch (Exception e) {
                e.printStackTrace();
                msg = Result.newFailInstance(MsgConstants.DEL_FAIL + e.getMessage());
            }
            return msg;
        }
        return Result.newFailInstance(SystemConstants.ROLE_FAIL);
    }

    /**
     * 查询
     */
    @RequestMapping("/bizFlow-findList")
    @ResponseBody
    public Page<BizFlow> findList(User user) {
        String comId = user.getCompany().getId();// get from user
        try {
            Filter filters = new Filter();
            if (null == filters) {
                filters = new Filter();
                filters.setGroupOp(FilterGroupOption.AND);
            }
            SearchRule rule = new SearchRule("COM_ID", SearchRuleOption.eq, comId);
            filters.addRule(rule);
//            page = initPage(bizFlowBiz.findEntityCount(filters));
//            Order order = new Order();
//            if (null != sidx && !"".equals(sidx)) {
//                order.add(sidx, sord);
//            }
//            bizFlows = bizFlowBiz.findByJqgrid(page.getCurrentPageStartNo(), page
//                    .getPageSize(), filters, order);
            Pageable page = new PageRequest(0, 10, Sort.Direction.DESC);
            Jqgrid jqgrid = new Jqgrid(filters, page);
            Page<BizFlow> bizFlows = bizFlowBiz.findByJqgrid(jqgrid);
            if (bizFlows.getSize() > 0) {
                return bizFlows;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void setBizFlowBiz(BizFlowBiz bizFlowBiz) {
        this.bizFlowBiz = bizFlowBiz;
    }

}
